import axios from "axios";

const http = axios.create({
  baseURL: "http://192.168.110.249/mt/",
  timeout: 10000,
});

//请求拦截器
http.interceptors.request.use(
  (config) => {
    // 在发送请求之前做某事
    let token = sessionStorage.getItem("token") || "";
    config.headers["token"] = token;
    //接受JSON数据格式
    config.headers["Content-Type"] = "application/json;charset=utf-8";
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

//响应拦截器
http.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    if (response.data.code == 0) {
      return response.data;
    } else if (response.data.code == 10021) {
      //token失效
      alert(response.data.msg);
      window.location.href = "http://192.168.110.249/mt/" + "/mt/login.html";
      return Promise.reject(response.data.msg);
    }
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

//导出http对象
export default http;
